<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'

const filters = [
  { label: '全部', value: 'all' },
  { label: 'A级企业', value: 'a' },
  { label: 'B级企业', value: 'b' },
  { label: 'C级企业', value: 'c' }
]

const currentFilter = ref('all')
const sortOrder = ref('desc')

const rankings = ref([
  { id: 1, name: '上海智慧系统有限公司', rating: 'AAA', score: 93, trend: 'up', change: '+2.5' },
  { id: 2, name: '杭州云计算科技有限公司', rating: 'AAA', score: 92, trend: 'up', change: '+1.8' },
  { id: 3, name: '成都创新科技有限公司', rating: 'AA', score: 91, trend: 'stable', change: '0.0' },
  { id: 4, name: '武汉数字技术有限公司', rating: 'AA', score: 90, trend: 'down', change: '-1.2' },
  { id: 5, name: '深圳智能科技有限公司', rating: 'A', score: 88, trend: 'up', change: '+3.0' },
  { id: 6, name: '北京网络科技有限公司', rating: 'BBB', score: 85, trend: 'down', change: '-0.8' },
  { id: 7, name: '广州软件科技有限公司', rating: 'BB', score: 82, trend: 'stable', change: '0.0' },
  { id: 8, name: '南京电子科技有限公司', rating: 'B', score: 78, trend: 'up', change: '+1.5' },
  { id: 9, name: '湖南电子科技有限公司', rating: 'B', score: 79, trend: 'down', change: '-1.5' },
  { id: 10, name: '北京电子科技有限公司', rating: 'B', score: 80, trend: 'up', change: '+1.4' },
  { id: 11, name: '天津电子科技有限公司', rating: 'B', score: 82, trend: 'up', change: '+1.3' },
  { id: 12, name: '南宁电子科技有限公司', rating: 'B', score: 83, trend: 'up', change: '+1.2' },
  { id: 13, name: '昆明电子科技有限公司', rating: 'B', score: 84, trend: 'up', change: '+2.5' }
])

const sortedRankings = computed(() => {
  let filtered = rankings.value
  if (currentFilter.value !== 'all') {
    filtered = rankings.value.filter(item => 
      item.rating.toLowerCase().startsWith(currentFilter.value)
    )
  }
  
  return filtered.sort((a, b) => {
    return sortOrder.value === 'desc' ? b.score - a.score : a.score - b.score
  })
})

const getTrendIcon = (trend) => {
  const icons = {
    up: 'fas fa-arrow-up',
    down: 'fas fa-arrow-down',
    stable: 'fas fa-minus'
  }
  return icons[trend]
}

const getFilterCount = (value) => {
  if (value === 'all') return rankings.value.length
  return rankings.value.filter(item => 
    item.rating.toLowerCase().startsWith(value)
  ).length
}

const getCrownColor = (index) => {
  const colors = ['#FFD700', '#C0C0C0', '#CD7F32']
  return colors[index] || '#F59E0B'
}

const pageSize = 5 // 每页显示数量
const currentIndex = ref(0)
const isScrolling = ref(true)
let autoScrollTimer

// 计算显示的数据（包括重复项以实现无缝滚动）
const displayRankings = computed(() => {
  const items = [...sortedRankings.value]
  return [...items, ...items] // 复制一份数据
})

// 计算滚动样式
const scrollStyle = computed(() => {
  const translateY = -currentIndex.value * 60 // 60px 是每行高度
  return {
    transform: `translateY(${translateY}px)`,
    transition: isScrolling.value ? 'transform 0.6s ease-in-out' : 'none'
  }
})

// 计算总页数
const totalPages = computed(() => 
  Math.ceil(sortedRankings.value.length / pageSize)
)

const isPaused = ref(false)

// 自动轮播
const startAutoScroll = () => {
  stopAutoScroll()
  autoScrollTimer = window.setInterval(() => {
    if (isPaused.value) return
    
    if (currentIndex.value >= sortedRankings.value.length) {
      // 当滚动到复制的数据时，立即重置到原始位置
      isScrolling.value = false
      currentIndex.value = 0
      // 在下一帧恢复动画
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          isScrolling.value = true
        })
      })
    } else {
      isScrolling.value = true
      currentIndex.value++
    }
  }, 3000)
}

// 停止轮播
const stopAutoScroll = () => {
  if (autoScrollTimer) {
    clearInterval(autoScrollTimer)
  }
}

// 暂停滚动
const pauseScroll = () => {
  isPaused.value = true
}

// 恢复滚动
const resumeScroll = () => {
  isPaused.value = false
}

// 手动切换页面
const changePage = (page) => {
  if (page === currentIndex.value) return
  currentIndex.value = page
  stopAutoScroll()
  startAutoScroll()
}

// 监听筛选变化，重置位置
watch([currentFilter, sortOrder], () => {
  isScrolling.value = false
  currentIndex.value = 0
  nextTick(() => {
    isScrolling.value = true
    startAutoScroll()
  })
})

// 添加拖动相关状态
const isDragging = ref(false)
const startY = ref(0)
const startScrollTop = ref(0)
const lastDragTime = ref(0)
const dragSpeed = ref(0)

// 处理滚轮事件
const handleWheel = (e) => {
  isPaused.value = true
  
  const delta = e.deltaY
  const newIndex = currentIndex.value + Math.sign(delta)
  
  if (newIndex >= 0 && newIndex < sortedRankings.value.length) {
    currentIndex.value = newIndex
  }
  
  // 重置自动滚动计时器
  clearTimeout(autoResumeTimer.value)
  autoResumeTimer.value = window.setTimeout(() => {
    isPaused.value = false
  }, 2000)
}

// 开始拖动
const startDrag = (e) => {
  isDragging.value = true
  startY.value = e.clientY
  startScrollTop.value = currentIndex.value * 60
  dragSpeed.value = 0
  lastDragTime.value = Date.now()
  document.body.style.userSelect = 'none'
}

// 拖动中
const onDrag = (e) => {
  if (!isDragging.value) return
  
  const deltaY = e.clientY - startY.value
  const newScrollTop = startScrollTop.value - deltaY
  const newIndex = Math.round(newScrollTop / 60)
  
  if (newIndex >= 0 && newIndex < sortedRankings.value.length) {
    currentIndex.value = newIndex
  }
  
  // 计算拖动速度
  const now = Date.now()
  const timeDelta = now - lastDragTime.value
  if (timeDelta > 0) {
    dragSpeed.value = deltaY / timeDelta
  }
  lastDragTime.value = now
}

// 停止拖动
const stopDrag = () => {
  if (!isDragging.value) return
  
  isDragging.value = false
  document.body.style.userSelect = ''
  
  // 添加惯性滚动
  if (Math.abs(dragSpeed.value) > 0.5) {
    const momentum = dragSpeed.value * 15
    const targetIndex = Math.round(
      currentIndex.value - momentum
    )
    
    isScrolling.value = true
    currentIndex.value = Math.max(0, Math.min(
      targetIndex,
      sortedRankings.value.length - 1
    ))
  }
  
  // 2秒后恢复自动滚动
  clearTimeout(autoResumeTimer.value)
  autoResumeTimer.value = window.setTimeout(() => {
    isPaused.value = false
  }, 2000)
}

// 自动恢复计时器
let autoResumeTimer = ref()

onMounted(() => {
  startAutoScroll()
})

onUnmounted(() => {
  stopAutoScroll()
  if (autoResumeTimer.value) {
    clearTimeout(autoResumeTimer.value)
  }
})
</script>
<template>
  <div class="panel-card">
    <div class="panel-header">
      <div class="header-title">
        <i class="fas fa-trophy"></i>
        企业信用排行榜
        <span class="total-count">共 {{ sortedRankings.length }} 家</span>
      </div>
      <div class="header-actions">
        <div class="filter-group">
          <button 
            v-for="filter in filters" 
            :key="filter.value"
            :class="['filter-btn', { active: currentFilter === filter.value }]"
            @click="currentFilter = filter.value"
          >
            {{ filter.label }}
            <span class="count">{{ getFilterCount(filter.value) }}</span>
          </button>
        </div>
      </div>
    </div>
    
    <div class="table-wrapper">
      <div class="table-viewport" 
        @mouseenter="pauseScroll" 
        @mouseleave="resumeScroll"
        @wheel.prevent="handleWheel"
        @mousedown.prevent="startDrag"
        @mousemove.prevent="onDrag"
        @mouseup="stopDrag"
      >
        <div class="table-scroll" 
          :style="scrollStyle"
          :class="{ 'dragging': isDragging }"
        >
          <table class="ranking-table">
            <thead>
              <tr>
                <th class="rank-col">排名</th>
                <th class="name-col">企业名称</th>
                <th class="rating-col">信用等级</th>
                <th class="score-col">
                  <div class="score-header">
                    <span>信用分数</span>
                    <div class="sort-icons">
                      <i class="fas fa-caret-up" :class="{ active: sortOrder === 'asc' }" @click="sortOrder = 'asc'"></i>
                      <i class="fas fa-caret-down" :class="{ active: sortOrder === 'desc' }" @click="sortOrder = 'desc'"></i>
                    </div>
                  </div>
                </th>
                <th class="trend-col">趋势</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in displayRankings" 
                :key="`${item.id}-${index}`"
                class="ranking-row"
                :class="{ 'top-three': index % pageSize < 3 }"
              >
                <td class="rank-col">
                  <div class="rank-number">
                    {{ (index % sortedRankings.length) + 1 }}
                    <i v-if="index % sortedRankings.length < 3" 
                      class="fas fa-crown crown-icon" 
                      :style="{ color: getCrownColor(index % sortedRankings.length) }"
                    ></i>
                  </div>
                </td>
                <td class="name-col">
                  <div class="company-name">{{ item.name }}</div>
                </td>
                <td class="rating-col">
                  <span class="rating-badge" :class="item.rating.toLowerCase()">
                    {{ item.rating }}
                  </span>
                </td>
                <td class="score-col">
                  <div class="score">
                    {{ item.score }}
                    <span class="score-unit">分</span>
                  </div>
                </td>
                <td class="trend-col">
                  <div class="trend" :class="item.trend">
                    <i :class="getTrendIcon(item.trend)"></i>
                    {{ item.change }}
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="pagination">
      <div v-for="page in totalPages" 
        :key="page"
        class="page-dot"
        :class="{ active: currentIndex === page - 1 }"
        @click="changePage(page - 1)"
      ></div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.panel-card {
  background: rgba(30, 41, 59, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 20px;
  backdrop-filter: blur(8px);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.header-title {
  color: #94A3B8;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  
  i {
    color: #F59E0B;
    font-size: 18px;
  }

  .total-count {
    margin-left: 8px;
    font-size: 13px;
    color: #64748B;
    font-weight: normal;
  }
}

.filter-group {
  display: flex;
  gap: 1px;
  padding: 2px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
}

.filter-btn {
  background: none;
  border: none;
  padding: 6px 12px;
  font-size: 13px;
  color: #94A3B8;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover:not(.active) {
    color: #E2E8F0;
  }
  
  &.active {
    background: rgba(96, 165, 250, 0.2);
    color: #60A5FA;
  }

  position: relative;
  
  .count {
    margin-left: 4px;
    font-size: 12px;
    opacity: 0.7;
  }
  
  &.active .count {
    opacity: 1;
  }
}

.table-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.table-viewport {
  position: relative;
  height: 300px;
  overflow: hidden;
  cursor: grab;
  
  &:active {
    cursor: grabbing;
  }
}

.table-scroll {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  will-change: transform;
  user-select: none;
  
  &.dragging {
    transition: none !important;
  }
}

.ranking-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  
  thead {
    position: sticky;
    top: 0;
    z-index: 10;
    background: rgba(30, 41, 59, 0.95);
  }
  
  tbody tr {
    height: 60px;
    transition: background-color 0.3s ease;
    cursor: pointer;
    
    &:hover {
      background: rgba(255, 255, 255, 0.08);
    }
    
    &.top-three {
      background: linear-gradient(90deg, 
        rgba(96, 165, 250, 0.1), 
        rgba(96, 165, 250, 0.02)
      );
      
      &:hover {
        background: linear-gradient(90deg, 
          rgba(96, 165, 250, 0.15), 
          rgba(96, 165, 250, 0.05)
        );
      }
    }
  }
}

.sort-icons {
  display: flex;
  flex-direction: column;
  gap: 2px;
  
  i {
    font-size: 10px;
    color: #475569;
    cursor: pointer;
    transition: color 0.3s ease;
    
    &:hover, &.active {
      color: #60A5FA;
    }
  }
}

.rank-number {
  position: relative;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'JetBrains Mono', monospace;
  font-weight: 600;
  
  .crown-icon {
    position: absolute;
    top: -8px;
    left: 50%;
    transform: translateX(-50%);
    color: #F59E0B;
    font-size: 10px;
    transition: transform 0.3s ease;
  }
  
  &:hover .crown-icon {
    transform: translateX(-50%) scale(1.2) rotate(-12deg);
  }
}

.rating-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-family: 'JetBrains Mono', monospace;
  transition: transform 0.3s ease;
  
  &:hover {
    transform: scale(1.05);
  }
  
  &.aaa {
    background: rgba(16, 185, 129, 0.1);
    color: #10B981;
  }
  
  &.aa {
    background: rgba(96, 165, 250, 0.1);
    color: #60A5FA;
  }
  
  &.a {
    background: rgba(139, 92, 246, 0.1);
    color: #8B5CF6;
  }
  
  &.bbb, &.bb, &.b {
    background: rgba(245, 158, 11, 0.1);
    color: #F59E0B;
  }
}

.trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 13px;
  transition: transform 0.3s ease;
  
  &.up {
    color: #10B981;
  }
  
  &.down {
    color: #EF4444;
  }
  
  &.stable {
    color: #94A3B8;
  }
  
  i {
    font-size: 10px;
  }
  
  &.up:hover i {
    transform: translateY(-2px);
  }
  
  &.down:hover i {
    transform: translateY(2px);
  }
}

.rank-col { width: 80px; min-width: 80px; }
.name-col { width: auto; min-width: 200px; }
.rating-col { width: 120px; min-width: 120px; }
.score-col { width: 120px; min-width: 120px; }
.trend-col { width: 100px; min-width: 100px; }

.company-name {
  position: relative;
  padding-left: 12px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: #60A5FA;
    transform: translateY(-50%);
  }
}

.score {
  font-family: 'JetBrains Mono', monospace;
  font-weight: 600;
  
  .score-unit {
    margin-left: 2px;
    font-size: 12px;
    opacity: 0.7;
    font-weight: normal;
  }
}

.ranking-row {
  opacity: 1;
  transform: none;
  animation: none;
  transition: opacity 0.3s ease;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 8px;
  padding: 12px 0;
  
  .page-dot {
    position: relative;
    width: 6px;
    height: 6px;
    
    &::after {
      content: '';
      position: absolute;
      top: -4px;
      left: -4px;
      right: -4px;
      bottom: -4px;
      border-radius: 50%;
      background: transparent;
      transition: background-color 0.3s ease;
    }
    
    &:hover::after {
      background: rgba(96, 165, 250, 0.1);
    }
    
    &.active {
      width: 18px;
      
      &::after {
        border-radius: 3px;
      }
    }
  }
}

// 优化渐变遮罩
.table-wrapper::after {
  background: linear-gradient(
    to top,
    rgba(30, 41, 59, 1) 0%,
    rgba(30, 41, 59, 0.8) 40%,
    transparent 100%
  );
}

.table-wrapper::before {
  background: linear-gradient(
    to bottom,
    rgba(30, 41, 59, 1) 0%,
    rgba(30, 41, 59, 0.8) 40%,
    transparent 100%
  );
}

// 添加滚动提示
.table-viewport::after {
  content: '';
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/></svg>');
  background-size: 24px;
  background-position: center;
  background-repeat: no-repeat;
}

.table-viewport:hover::after {
  opacity: 0.5;
}
</style> 